package com.knowledgeqa.system.service.impl;

import com.knowledgeqa.system.entity.User;
import com.knowledgeqa.system.exception.BusinessException;
import com.knowledgeqa.system.mapper.UserMapper;
import com.knowledgeqa.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public boolean register(User user) {
        // 检查用户名、手机号、邮箱是否已存在
        if (userMapper.selectByUsername(user.getUsername()) != null) {
            throw new BusinessException("用户名已存在");
        }
        if (userMapper.selectByPhone(user.getPhone()) != null) {
            throw new BusinessException("手机号已被注册");
        }
        if (userMapper.selectByEmail(user.getEmail()) != null) {
            throw new BusinessException("邮箱已被注册");
        }
        
        // 暂时不进行密码加密
        // 后续如需安全考虑，可添加密码加密逻辑
        
        // 设置默认值
        user.setCoinBalance(0);
        user.setRole(0); // 普通用户
        user.setStatus(0); // 正常状态
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        
        return userMapper.insert(user) > 0;
    }

    @Override
    public User login(String username, String password) {
        // 根据用户名查询用户
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 检查用户状态
        if (user.getStatus() != 0) {
            throw new BusinessException("用户已被禁用");
        }
        
        // 简单密码验证（暂时不考虑安全问题）
        if (!password.equals(user.getPassword())) {
            throw new BusinessException("密码错误");
        }
        
        // 隐藏密码信息
        user.setPassword(null);
        return user;
    }

    @Override
    public User findById(Long id) {
        User user = userMapper.selectById(id);
        if (user != null) {
            // 隐藏密码信息
            user.setPassword(null);
        }
        return user;
    }
    
    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public boolean update(User user) {
        // 检查用户是否存在
        User existingUser = userMapper.selectById(user.getId());
        if (existingUser == null) {
            throw new BusinessException("用户不存在");
        }
        
        user.setUpdateTime(new Date());
        return userMapper.update(user) > 0;
    }

    @Override
    public boolean updateAvatar(Long userId, String avatar) {
        User user = new User();
        user.setId(userId);
        user.setAvatar(avatar);
        user.setUpdateTime(new Date());
        return userMapper.update(user) > 0;
    }

    @Override
    @Transactional
    public boolean rechargeCoin(Long userId, Integer amount) {
        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 检查金额是否合法
        if (amount <= 0) {
            throw new BusinessException("充值金额必须大于0");
        }
        
        // 增加用户金币余额
        return userMapper.updateCoinBalance(userId, amount) > 0;
    }

    @Override
    @Transactional
    public boolean consumeCoin(Long userId, Integer amount, Integer type, String remark) {
        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
package com.knowledgeqa.system.service.impl;

import com.knowledgeqa.system.entity.User;
import com.knowledgeqa.system.mapper.UserMapper;
import com.knowledgeqa.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.knowledgeqa.system.exception.BusinessException;

/**
 * 用户服务实现类
 */
        @Service
        public class UserServiceImpl implements UserService {

            @Autowired
            private UserMapper userMapper;

            @Override
            @Transactional
            public boolean register(User user) {
                // 检查用户名、手机号、邮箱是否已存在
                if (userMapper.selectByUsername(user.getUsername()) != null) {
                    throw new BusinessException("用户名已存在");
                }
                if (userMapper.selectByPhone(user.getPhone()) != null) {
                    throw new BusinessException("手机号已被注册");
                }
                if (userMapper.selectByEmail(user.getEmail()) != null) {
                    throw new BusinessException("邮箱已被注册");
                }

                // 暂时不进行密码加密
                // 后续如需安全考虑，可添加密码加密逻辑

                // 设置默认值
                user.setCoinBalance(0);
                user.setRole(0); // 普通用户
                user.setStatus(0); // 正常状态
                user.setCreateTime(new Date());
                user.setUpdateTime(new Date());

                return userMapper.insert(user) > 0;
            }

            @Override
            public User login(String username, String password) {
                // 根据用户名查询用户
                User user = userMapper.selectByUsername(username);
                if (user == null) {
                    throw new BusinessException("用户不存在");
                }

                // 检查用户状态
                if (user.getStatus() != 0) {
                    throw new BusinessException("用户已被禁用");
                }

                // 简单密码验证（暂时不考虑安全问题）
                if (!password.equals(user.getPassword())) {
                    throw new BusinessException("密码错误");
                }

                // 隐藏密码信息
                user.setPassword(null);
                return user;
            }

            @Override
            public User findById(Long id) {
                User user = userMapper.selectById(id);
                if (user != null) {
                    // 隐藏密码信息
                    user.setPassword(null);
                }
                return user;
            }

            @Override
            public User getUserByUsername(String username) {
                return userMapper.selectByUsername(username);
            }

            @Override
            public boolean update(User user) {
                // 检查用户是否存在
                User existingUser = userMapper.selectById(user.getId());
                if (existingUser == null) {
                    throw new BusinessException("用户不存在");
                }

                user.setUpdateTime(new Date());
                return userMapper.update(user) > 0;
            }

            @Override
            public String updateAvatar(Long userId, String base64Image) {
                // 检查用户是否存在
                User user = userMapper.selectById(userId);
                if (user == null) {
                    throw new BusinessException("用户不存在");
                }

                try {
                    // 提取base64数据（去掉data:image/jpeg;base64,部分）
                    String[] parts = base64Image.split(",");
                    String imageData = parts.length > 1 ? parts[1] : parts[0];

                    // 解码base64数据
                    byte[] imageBytes = Base64.getDecoder().decode(imageData);

                    // 生成唯一的文件名
                    String fileName = "avatar_" + userId + "_" + UUID.randomUUID() + ".jpg";

                    // 确定保存路径 - 使用绝对路径，保存到webapp/static/imgs目录
                    String filePath = "d:\\hjdgadk\\KnowledgeQASystem\\src\\main\\webapp\\static\\imgs\\" + fileName;

                    // 确保目录存在
                    File directory = new File("d:\\hjdgadk\\KnowledgeQASystem\\src\\main\\webapp\\static\\imgs");
                    if (!directory.exists()) {
                        directory.mkdirs();
                    }

                    // 保存文件
                    try (FileOutputStream fos = new FileOutputStream(filePath)) {
                        fos.write(imageBytes);
                    }

                    // 构建相对路径（前端可以访问的路径）
                    String relativePath = "/knowledge-qa/static/imgs/" + fileName;

                    // 更新用户头像路径
                    user.setAvatar(relativePath);
                    user.setUpdateTime(new Date());
                    userMapper.update(user);

                    return relativePath;
                } catch (Exception e) {
                    throw new BusinessException("头像保存失败：" + e.getMessage());
                }
            }

            @Override
            @Transactional
            public boolean rechargeCoin(Long userId, Integer amount) {
                // 检查用户是否存在
                User user = userMapper.selectById(userId);
                if (user == null) {
                    throw new BusinessException("用户不存在");
                }

                // 检查金额是否合法
                if (amount <= 0) {
                    throw new BusinessException("充值金额必须大于0");
                }

                // 增加用户金币余额
                return userMapper.updateCoinBalance(userId, amount) > 0;
            }

            @Override
            @Transactional
            public boolean consumeCoin(Long userId, Integer amount, Integer type, String remark) {
                // 检查用户是否存在
                User user = userMapper.selectById(userId);
                if (user == null) {
                    throw new BusinessException("用户不存在");
                }

                // 检查金额是否合法
                if (amount <= 0) {
                    throw new BusinessException("消费金额必须大于0");
                }

                // 检查金币余额是否充足
                if (user.getCoinBalance() < amount) {
                    throw new BusinessException("金币余额不足");
                }

                // 减少用户金币余额
                return userMapper.updateCoinBalance(userId, -amount) > 0;
            }

            @Override
            public Integer getCoinBalance(Long userId) {
                User user = userMapper.selectById(userId);
                return user != null ? user.getCoinBalance() : 0;
            }

            @Override
            public List<User> findAll() {
                List<User> users = userMapper.selectAll();
                // 隐藏所有用户的密码信息
                for (User user : users) {
                    user.setPassword(null);
                }
                return users;
            }

            @Override
            public boolean updateUserStatus(Long userId, Integer status) {
                return userMapper.updateStatus(userId, status) > 0;
            }

            @Override
            public String getUsernameById(Long userId) {
                User user = userMapper.selectById(userId);
                if (user != null) {
                    // 优先返回昵称，如果没有昵称则返回"用户+用户ID"
                    if (user.getNickname() != null && !user.getNickname().isEmpty()) {
                        return user.getNickname();
                    } else {
                        return "用户" + userId;
                    }
                }
                return null;
            }

            @Override
            @Transactional
            public boolean deleteUser(Long userId) {
                // 检查用户是否存在
                User user = userMapper.selectById(userId);
                if (user == null) {
                    throw new BusinessException("用户不存在");
                }

                // 如果用户有头像，删除头像文件
                if (user.getAvatar() != null && !user.getAvatar().isEmpty()) {
                    try {
                        // 构建头像文件的绝对路径
                        String avatarPath = user.getAvatar();
                        // 去掉URL前缀，获取相对路径
                        String relativePath = avatarPath.replace("/knowledge-qa", "");
                        // 构建绝对路径
                        String absolutePath = "d:\\hjdgadk\\KnowledgeQASystem\\src\\main\\webapp" + relativePath;

                        File avatarFile = new File(absolutePath);
                        if (avatarFile.exists()) {
                            boolean deleted = avatarFile.delete();
                            if (!deleted) {
                                // 记录日志，但不影响用户删除操作
                                System.err.println("删除头像文件失败: " + absolutePath);
                            }
                        }
                    } catch (Exception e) {
                        // 记录日志，但不影响用户删除操作
                        System.err.println("删除头像文件异常: " + e.getMessage());
                    }
                }

                // 删除用户记录
                return userMapper.deleteById(userId) > 0;
            }
        }